package com.tanhua.dubbo.server.api;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.PageUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.dubbo.config.annotation.Service;
import com.tanhua.dubbo.server.enums.IdType;
import com.tanhua.dubbo.server.pojo.FollowUser;
import com.tanhua.dubbo.server.pojo.Video;
import com.tanhua.dubbo.server.service.IdService;
import com.tanhua.dubbo.server.vo.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.ArrayList;
import java.util.List;

@Service(version = "1.0.0")
@Slf4j
public class VideoApiImpl implements VideoApi {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private IdService idService;

    private static final String VIDEO_FOLLOW_USER_KEY_PREFIX = "VIDEO_FOLLOW_USER_";

    private String getVideoFollowUserKey(Long userID) {
        return VIDEO_FOLLOW_USER_KEY_PREFIX + userID;
    }

    /**
     * 查看小视频列表
     *
     * @param id
     * @param page
     * @param pageSize
     * @return
     */
    @Override
    public PageInfo<Video> findVideoList(Long id, Integer page, Integer pageSize) {
        PageInfo<Video> pageInfo = new PageInfo<>();
        pageInfo.setPageNum(page);
        pageInfo.setPageSize(pageSize);
        //从redis中获取推荐视频的数据
        String redisKey = "QUANZI_VIDEO_RECOMMEND_" + id;
        String data = redisTemplate.opsForValue().get(redisKey);

        List<Long> videos = new ArrayList<>();
        int recommendCount = 0;
        if (StrUtil.isNotEmpty(data)) {
            //手动分页查询数据
            List<String> dataList = StrUtil.split(data, ',');
            //计算分页数据
            int[] startEnd = PageUtil.transToStartEnd(page - 1, pageSize);
            int start = startEnd[0];
            int end = Math.min(startEnd[1], dataList.size());
            for (int i = start; i < end; i++) {
                videos.add(Convert.toLong(dataList.get(i)));
            }
            recommendCount = dataList.size();
        }
        if (CollUtil.isEmpty(videos)) {
            //没有推荐或前面推荐已经查询完毕，查询系统的视频数据
            //计算前面的推荐视频页数
            int totalPage = PageUtil.totalPage(recommendCount, pageSize);

            Pageable pageRequest = PageRequest.of(page - totalPage - 1, pageSize, Sort.by(Sort.Order.desc("created")));
            Query query = new Query().with(pageRequest);
            List<Video> videoList = mongoTemplate.find(query, Video.class);

            pageInfo.setRecords(videoList);
            return pageInfo;
        }
        //根据vid查询视频数据
        Query query = Query.query(Criteria.where("vid").in(videos));
        List<Video> list = mongoTemplate.find(query, Video.class);
        pageInfo.setRecords(list);
        return pageInfo;
    }

    /**
     * 发布小视频
     *
     * @param video
     * @return
     */
    @Override
    public String saveVideo(Video video) {
        try {
            if (!ObjectUtil.isAllNotEmpty(video.getUserId(), video.getPicUrl(), video.getVideoUrl())) {
                return null;
            }
            video.setId(ObjectId.get());
            video.setVid(idService.createId(IdType.VIDEO));
            video.setCreated(System.currentTimeMillis());
            mongoTemplate.save(video);

            return video.getId().toHexString();
        } catch (Exception e) {
            log.error("小视频发布失败~ video = " + video, e);
        }
        return null;
    }

    /**
     * 通过id查询单个视频
     *
     * @param videoId
     * @return
     */
    @Override
    public Video findVideoById(String videoId) {
        return mongoTemplate.findById(new ObjectId(videoId), Video.class);
    }

    /**
     * 关注小视频
     *
     * @param id     当前登录用户的ID
     * @param focusUserId 发布这条视频的用户的ID
     * @return
     */
    @Override
    public Boolean focusVideo(Long id, Long focusUserId) {
        if(!ObjectUtil.isAllNotEmpty(id,focusUserId)){
            return null;
        }
        try {
            //需要将用户的关注列表保存到redis中,方便后续查询
            Boolean cord = findFocusCord(id, focusUserId);
            if(cord){
                return false;
            }
            FollowUser followUser = new FollowUser();
            followUser.setId(ObjectId.get());
            followUser.setUserId(id);
            followUser.setLikeUserId(focusUserId);
            followUser.setCreated(System.currentTimeMillis());
            //保存到mongodb中
            mongoTemplate.save(followUser);
            //保存到redis
            String userKey = getVideoFollowUserKey(id);
            String hashKey = String.valueOf(focusUserId);
            redisTemplate.opsForHash().put(userKey,hashKey,"1");
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 查看是否关注小视频的方法
     *
     * @param userId  当前登录用户的ID
     * @param focusUserId 被关注目标用户的ID
     * @return
     */
    @Override
    public Boolean findFocusCord(Long userId, Long focusUserId) {
        String userKey = getVideoFollowUserKey(userId);
        String hashKey = String.valueOf(focusUserId);
        //先去redis中查询是否由这个键
        Boolean data = redisTemplate.opsForHash().hasKey(userKey, hashKey);
        //有就返回true
        if(data){
            return true;
        }
        //如果没有就再去数据库中查询,以免redis数据丢失
        Query query = Query.query(Criteria.where("userId").is(userId).and("likeUserId").is(focusUserId));
        List<Video> videos = mongoTemplate.find(query, Video.class);
        if(CollUtil.isNotEmpty(videos)){
            return true;
        }
        return false;
    }

    /**
     * 取消关注视频的方法
     * @param userId 当前登录用户ID
     * @param focusUserId 被关注目标用户ID
     * @return
     */
    @Override
    public Boolean unFocusVideo(Long userId, Long focusUserId) {
        if(!ObjectUtil.isAllNotEmpty(userId,focusUserId)){
            return false;
        }
        Boolean cord = findFocusCord(userId, focusUserId);
        if(!cord){
            return false;
        }
        String userKey = getVideoFollowUserKey(userId);
        String hashKey = String.valueOf(focusUserId);
        redisTemplate.opsForHash().delete(userKey,hashKey);

        Query query = Query.query(Criteria.where("userId").is(userId).and("likeUserId").is(focusUserId));
        mongoTemplate.remove(query,Video.class);
        return true;
    }
}
